import { CheckAns } from "./CheckAns";

namespace LeetCode0007Reverse {

    // 直接当作string反转
    function reverse(x: number): number {
        // 检测输入的合法性
        const numLimit: number = Math.pow(2, 31);
        if (!x || x > numLimit - 1 || x < -numLimit)
            return 0;

        const isMinus: boolean = x < 0;
        const numStr = (isMinus ? -x : x).toString().split('').reverse().join('');
        const num: number = (isMinus ? -1 : 1) * (Number(numStr) || 0);
        return (num < -numLimit || num > numLimit - 1) ? 0 : num;
    };

    // 数值运算
    function reverse1(x: number): number {
        // 检测输入的合法性
        const INT_MAX: number = Math.pow(2, 31) - 1;
        const INT_MIN: number = -Math.pow(2, 31);
        if (!x || x > INT_MAX || x < INT_MIN)
            return 0;

        const OVER_FLOW = Math.floor(INT_MAX / 10);
        let rev: number = 0;
        while (x != 0) {
            const right: number = x % 10;
            // 防止出现小数
            x = (x - right) / 10;
            if (rev > OVER_FLOW || (rev == OVER_FLOW && right > 7))
                return 0;
            if (rev < -OVER_FLOW || (rev == -OVER_FLOW && right < -8))
                return 0;
            rev = rev * 10 + right;
        }
        return rev;
    }

    // test
    const testData: { s: number, ans: number }[] = [
        { s: 123, ans: 321 },
        { s: -123, ans: -321 },
        { s: 120, ans: 21 },
        { s: 0, ans: 0 }
    ];
    for (const data of testData) {
        const ans = reverse1(data.s);
        CheckAns(data, ans);
    }
}
